//
//  XHRSeeBigPictureViewController.m
//  BuDeJie
//
//  Created by haoran on 16/4/16.
//  Copyright © 2016年 xuhaoran. All rights reserved.
//

#import "XHRSeeBigPictureViewController.h"
#import "XHRTopicItem.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import <Photos/Photos.h>

@interface XHRSeeBigPictureViewController()<UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIButton *savaButton;

/** 要显示的图片 **/
@property (nonatomic, weak) UIImageView *imageView;

/* 自动生成的内容：number的getter\setter声明+实现、_number成员变量*/
//@property (nonatomic, assign) NSInteger number;

/* 自动生成的内容：number的getter声明+实现、_number成员变量*/
//@property (nonatomic, assign, readonly) NSInteger number;

// 在interface中写方法的生命,是为了点语法的智能提示
-(PHFetchResult<PHAsset *> * )createdAssets;

-(PHAssetCollection *)createdCollection;

@end

@implementation XHRSeeBigPictureViewController


-(void)viewDidLoad{
    
    // scrollView
    [self setupContent];
    
    
}



/**
 *  创建scrollView
 */
-(void)setupContent{
    
    // scrollView
    UIScrollView *scrollView = [[UIScrollView alloc]init];
//    scrollView.backgroundColor = [UIColor redColor];
    scrollView.frame = [UIScreen mainScreen].bounds;
    [self.view insertSubview:scrollView atIndex:0];
    
    [scrollView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(back:)]];
    
    // imageView
    UIImageView *imageView = [[UIImageView alloc]init];
    [imageView sd_setImageWithURL:[NSURL URLWithString: self.topicItem.image1] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if(image == nil) return ;
        
        self.savaButton.enabled = YES;
            
            }];
    
    imageView.xhr_width = scrollView.xhr_width;
    imageView.xhr_x = 0;
    [scrollView addSubview:imageView];
    self.imageView = imageView;
    
    // 处理高度
    imageView.xhr_height =  imageView.xhr_width * self.topicItem.height / self.topicItem.width;
    if (imageView.xhr_height >= XHRScreenH) { //长图
        
        imageView.xhr_y = 0;
        scrollView.contentSize = CGSizeMake(0, imageView.xhr_height);
    }else{
        imageView.xhr_CenterY = scrollView.xhr_height * 0.5;
    }
    
    // 图片缩放
    CGFloat scale = self.topicItem.height / scrollView.xhr_height;
    if (scale > 1.0) {  //增加缩放功能
        scrollView.maximumZoomScale = scale;
        // 设置代理
        scrollView.delegate = self;
        
        
    }
    
}


#pragma mark - 点击事件
- (IBAction)back:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

/**
 *  点击保存图片到相册
 */
- (IBAction)saveButtonClick:(id)sender {
    
  
    /*
     requestAuthorization方法的功能
     1.如果用户还没有做过选择，这个方法就会弹框让用户做出选择
     1> 用户做出选择以后才会回调block
     
     2.如果用户之前已经做过选择，这个方法就不会再弹框，直接回调block，传递现在的授权状态给block
     */
    // PHAuthorizationStatusNotDetermined
    // 用户还没有对当前App授权过(用户从未点击过Don't Allow或者OK按钮)
    
    // PHAuthorizationStatusRestricted
    // 因为一些系统原因导致无法访问相册（比如家长控制）
    
    // PHAuthorizationStatusDenied
    // 用户已经明显拒绝过当前App访问相片数据（用户已经点击过Don't Allow按钮）
    
    // PHAuthorizationStatusAuthorized
    // 用户已经允许过当前App访问相片数据（用户已经点击过OK按钮）
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            switch (status) {
                case PHAuthorizationStatusAuthorized:
                    //  保存图片到相册
                    [self saveImageToAlbum];
                    break;
                
                case PHAuthorizationStatusDenied:
                    if(oldStatus == PHAuthorizationStatusNotDetermined) return ;
                    
                    XHRLog(@"提醒用户打开相册的访问开关");
                    break;
                
                case PHAuthorizationStatusRestricted:
                    [SVProgressHUD showErrorWithStatus:@"因系统原因,无法访问相册"];
                    break;
                    
                default:
                    break;
            }
        });
    }];

    
}


/**
 *  保存图片到相册
 */
-(void)saveImageToAlbum{

    PHFetchResult<PHAsset *> *createdAssets = self.createdAssets;
    
    PHAssetCollection * createdCollection = self.createdCollection;
    
    if (createdAssets == nil || createdCollection == nil) {
        [SVProgressHUD showErrorWithStatus:@"保存失败"];
        return;
    }
    
    // 将刚才添加到【相机胶卷】的图片，引用（添加）到【自定义相册】
    NSError * error = nil;
    [[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{
        PHAssetCollectionChangeRequest * request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:createdCollection];
        // 插入到相册第一张(作为相册封面图)
        [request insertAssets:createdAssets atIndexes:[NSIndexSet indexSetWithIndex:0]];
    } error:&error];
    
    // 保存结果
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"保存失败"];
    }else{
        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
    }
}



/**
 *  获得刚才添加到【相机胶卷】中的图片
 */
-(PHFetchResult<PHAsset *> * )createdAssets{
    
    __block NSString * createdAssetID = nil;
    // 添加图片到相机胶卷
    [[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{
        
        createdAssetID = [PHAssetChangeRequest creationRequestForAssetFromImage:self.imageView.image].placeholderForCreatedAsset.localIdentifier;
        
    } error:nil];
    
    if (createdAssetID == nil) return nil;
    
    // 保存完毕之后保存图片
    return [PHAsset fetchAssetsWithLocalIdentifiers:@[createdAssetID] options:nil];

}

/**
 *  获得【自定义相册】
 */
-(PHAssetCollection *)createdCollection{
    // 获取软件的名字作为相册的标题
    NSString * title = [NSBundle mainBundle].infoDictionary[(NSString *)kCFBundleNameKey];
    
      // 获取所有的自定义相册
    PHFetchResult<PHAssetCollection *> * collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection * collection in collections) {
        if ([collection.localizedTitle isEqualToString:title]) {
            return  collection;
            
        }
    }
    
    // 代码执行到这里，说明还没有自定义相册
    
    // 已创建的自定义相册
    __block NSString *createdCollectionId = nil;

    // 创建一个新的相册
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        createdCollectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title].placeholderForCreatedAssetCollection.localIdentifier;
    } error:nil];
    
    if (createdCollectionId == nil) return nil;
        // 创建完毕后再取出相册
        return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createdCollectionId] options:nil].firstObject;
    


}

#pragma mark - UIScrollViewDelegate

-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
   return  self.imageView;
}

@end
